package schudel.daniel.androidspellingquiz;

import java.util.ArrayList;
import java.util.ListIterator;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

public class SpellingListManagementActivity extends Activity {
    private static final String TAG = "SLMActivity: ";
    private String listName;
    private Spinner spinnerChooseList;
    private Spinner spinnerDeleteWord;
    private Button buttonDeleteWord;
    private Button buttonAddWord;
    private Button buttonDeleteList;
    private TextView textViewListStatus;
    private EditText editTextNewList;
    private EditText editTextAddWord;
    private int spinnerChooseListLastPosition;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "onCreate");
        setContentView(R.layout.activity_spelling_list_management);
        spinnerChooseList  = (Spinner) findViewById(R.id.spinnerChooseList);
        spinnerDeleteWord  = (Spinner) findViewById(R.id.spinnerDeleteWord);
    	buttonDeleteWord   = (Button)  findViewById(R.id.buttonDeleteWord);
    	buttonAddWord      = (Button)  findViewById(R.id.buttonAddWord);
    	buttonDeleteList   = (Button)  findViewById(R.id.buttonDeleteList);
    	textViewListStatus = (TextView)findViewById(R.id.textViewListStatus);
        editTextNewList    = (EditText)findViewById(R.id.editTextNewList);
        editTextAddWord    = (EditText)findViewById(R.id.editTextAddWord);
        spinnerChooseListLastPosition = -1;
    }

    protected void onStart() {
    	super.onStart();
        Log.d(TAG, "onStart");
        
        spinnerChooseList.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) { 
            	if (position != spinnerChooseListLastPosition) {
            		Log.d(TAG, "onItemSelected");
            		moveToList(String.valueOf(spinnerChooseList.getSelectedItem()));
            		spinnerChooseListLastPosition = position;
            	}
            } 

            public void onNothingSelected(AdapterView<?> adapterView) {
                return;
            } 
        }); 

//        Intent intent = getIntent();
//        moveToList(intent.getStringExtra(MainActivity.SPELLING_LIST_NAME));
    }
    
    protected void onRestart() {
        Log.d(TAG, "onRestart");
    	super.onRestart();
    }

    protected void onResume() {
        Log.d(TAG, "onResume");
    	super.onResume();
    }

    protected void onPause() {
        Log.d(TAG, "onPause");
    	super.onPause();
    }

    protected void onStop() {
        Log.d(TAG, "onStop");
    	super.onStop();
    }

    protected void onDestroy() {
        Log.d(TAG, "onDestroy");
    	super.onDestroy();
    }
    
    private void moveToList(String l) {
    	Log.d(TAG, "moveToList");
    	if (l == null) {
    		// if nothing requested (null), then take first list
            DB db = new DB(this);
            l = db.getFirstListName();
        }
        listName = l;
        addListNamesToSpinner();
        addWordsToSpinner();
        if (listName == "") {
        	setListWidgetStatus(false);
        	setTitle("Manage Lists");
        } else {
        	setListWidgetStatus(true);
        	setTitle("Manage List \"" + listName + "\"");
        }
        updateListStatus();
    }

    private void setListWidgetStatus(boolean status) {
    	buttonDeleteWord.setEnabled(status);
    	buttonAddWord.setEnabled(status);
    	buttonDeleteList.setEnabled(status);
    	spinnerChooseList.setEnabled(status);
    	spinnerDeleteWord.setEnabled(status);
    }
    
    private void updateListStatus() {
    	DB db = new DB(this);
        int count = db.getWords(listName).size();
        
        String status;
        switch (count) {
        	case 0:
        		status = "No words in list. Add a word!";
        		break;
        	case 1:
        		status = "1 word in list.";
        		break;
        	default:
        		status = "" + count + " words in list.";
        		break;
        }
        if (listName == "") {
        	status = "No lists! Add a new list.";
        }

    	textViewListStatus.setText(status);
    }
    
    private void addListNamesToSpinner() {
        DB db = new DB(this);
        ArrayList<String> items = db.getLists();

        ArrayAdapter<String> adapter = (ArrayAdapter<String>) spinnerChooseList.getAdapter();
        if (adapter == null) {
            adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, items);
            adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            spinnerChooseList.setAdapter(adapter);
        } else {
            adapter.clear();
            ListIterator<String> litr = items.listIterator();
            while (litr.hasNext()) {
                adapter.add(litr.next());
            }
            adapter.notifyDataSetChanged();
        }
        int pos = adapter.getPosition(listName);
        spinnerChooseList.setSelection(pos);
    }

    public void buttonOnClickAddList(View view) {
     	Log.d(TAG, "bittonOnClickAddList");
        String name = editTextNewList.getText().toString().trim();
        if (name.length() != 0) {
        	DB db = new DB(this);
        	db.addList(name);
        	Log.d("AddList: ", name);
        	editTextNewList.setText("");
            moveToList(name);
        }
    }     

    public void buttonOnClickDeleteWord(View view) {
    	Log.d(TAG, "buttonOnClickDeleteWord");
        String word = String.valueOf(spinnerDeleteWord.getSelectedItem());

        DB db = new DB(this);
        db.deleteWordFromList(listName, word);
        addWordsToSpinner();
    }   
    
    public void buttonOnClickAddWord(View view) {
    	Log.d(TAG, "buttonOnClickAddWord");
    	// Get contents
        String word = editTextAddWord.getText().toString().trim().toLowerCase();
        if (word.length() != 0) {
        	editTextAddWord.setText("");
        	DB db = new DB(this);
        	db.addWordToList(listName, word);
        	addWordsToSpinner();
        }
    }   
    
    public void buttonOnClickDeleteList(View view) {
    	AlertDialog.Builder builder = new AlertDialog.Builder(this);
    	builder.setMessage("Are you sure you want to delete \"" + listName + "\"?")
    	       .setCancelable(false)
    	       .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
    	           public void onClick(DialogInterface dialog, int id) {
    	        	   SpellingListManagementActivity.this.deleteList();
    	           }
    	       })
    	       .setNegativeButton("No", new DialogInterface.OnClickListener() {
    	           public void onClick(DialogInterface dialog, int id) {
    	                dialog.cancel();
    	           }
    	       });
    	AlertDialog alert = builder.create();
    	alert.show();
    }
    
    public void deleteList() {
    	Log.d(TAG, "deleteList");
    	DB db = new DB(this);
        db.deleteList(listName);
        moveToList(null);
    }   
    public void buttonOnClickDone(View view) {
        Intent myIntent = new Intent(this, MainActivity.class);
        startActivity(myIntent);
    }     
    
    private void addWordsToSpinner() {
        DB db = new DB(this);
        ArrayList<String> words = db.getWords(listName);
        
        ArrayAdapter<String> adapter;
        adapter = (ArrayAdapter<String>) spinnerDeleteWord.getAdapter();
        if (adapter == null) {
            Log.d(TAG, "Need new adapter");

        	adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, words);
        	adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        	spinnerDeleteWord.setAdapter(adapter);
        } else {
        	Log.d(TAG, "Reuse adapter");
        	adapter.clear();
        	ListIterator<String> litr = words.listIterator();
            while (litr.hasNext()) {
              adapter.add(litr.next());
            }
        	adapter.notifyDataSetChanged();
        }
        updateListStatus();
    }
}
